import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import vuexPersist from "vuex-persist";

export default new Vuex.Store({
  state: {
    list: [],
  },
  mutations: {
    setlist(state, val) {
      if (localStorage.getItem("vuex")) {
        state.list = JSON.parse(localStorage.getItem("vuex")).list;
      } else {
        state.list = val;
      }
      //每次都会调用 所以 需要从本地存储中拿数据 才能保证刷新不掉
    },
    remove(state, index) {
      state.list.splice(index, 1);
    },
  },
  getters: {
    price(state) {
      let num = 0;
      state.list.forEach((item) => {
        num += item.price * item.num;
      });
      return num;
    },
  },
  actions: {},
  modules: {},
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
  //插件 配置持久化插件
});
